<?php
namespace hema\delivery\engine;

use app\common\model\Setting;
use think\facade\Cache;
use hema\Http;

/**
 * 码科配送
*/
class Make extends Basics
{
	private $callback_url = 'task/delivery/make';	//订单状态回调
	
    /**
     * 构造函数
    */
    public function __construct($order){
		$config = Setting::getItem('webdelivery',0)['make'];
		parent::__construct($config, $order);
    }

	/**
     * 预发布订单创建
	*/
	public function preOrder()
	{
		$order = $this->order;
		$user = $order['address'];//收货人信息
		$shop = $order['shop'];//发货门店
		$url = $this->config['api_url'] . '/addons/make_speed/core/public/index.php/apis/v2/get_delivery_price';
        $queryarr = [
            'token' => $this->_token(), //令牌
            'fromcoord' => $shop['coordinate'],//起点地址坐标
            'tocoord' => $user['location'],//终点地址坐标
            'shop_id' => $shop['make_shop_id'] //店铺ID
        ];
        $result = json_decode(Http::get($url, $queryarr),true);
		if($result['error_code'] == 0){
			$distance = $result['data']['distance'] * 1000;//公里转换为米
			return [
				'delivery_time' => '30分钟',//预计送达时间
				'delivery_distance' => $distance . '米',//配送距离
				'delivery_price' => '￥' . $result['data']['total_price'] . '元', //配送费用
				'make' => $result
			];
		}
		$this->error = $result['msg'];
		return false;
	}

	/**
     * 创建订单
	*/
	public function addOrder($data=[])
	{
		$order = $this->order;
		$user = $order['address'];//收货人信息
		$user_location = explode(',',$user['location']);//拆分收货人定位经纬度
		$shop = $order['shop'];//发货门店
		$shop_location = explode(',',$shop['coordinate']);//拆分门店定位经纬度
		$post_data = [
			'token' => $this->_token(),//令牌
			'shop_id' => $shop['make_shop_id'],//$this->shop_id,//店铺ID
			'goods_name' => $shop['shop_name'],//商品名称
			'order_no' => $order['order_no'],//商家订单号	不允许重复
			'notify_url' => base_url() . $this->callback_url,//回调地址
			'pay_price' => $data['data']['total_price'],//跑腿支付金额
			'total_price' => $data['data']['total_price'],//跑腿总金额
			'pick_time' => date("Y-m-d H:i",time()),//取件时间 格式2020-09-30 00:00
			'remark' => $order['message'],//订单备注
		];
		//附加数据json格式，回调返回该参数
		$attach = [
			'name' => $shop['shop_name']
		];
		$post_data['attach'] = json_encode($attach,JSON_UNESCAPED_UNICODE);
		//地址信息
		$address = [
			'begin_detail' => $shop['address'],
			'begin_address' => $shop['province'] . $shop['city'] . $shop['district'] . $shop['address'],
			'begin_lat' => $shop_location[0],
			'begin_lng' => $shop_location[1],
			'begin_username' => $shop['linkman'],
			'begin_phone' => $shop['phone'],
			'end_detail' => $user['detail'],
			'end_address' => $user['province'] . $user['city'] . $user['district'] . $user['detail'],
			'end_lat' => $user_location[0],
			'end_lng' => $user_location[1],
			'end_username' => $user['name'],
			'end_phone' => $user['phone']
		];
		$post_data['address'] = json_encode($address,JSON_UNESCAPED_UNICODE);
		//商品详情
		$goods = [];
		foreach ($order['goods'] as $vo) {
			$goods[] = [
				'name' => $vo['goods_name'],//物品名称
				'price' => $vo['goods_price'],//物品价格
				'num' => $vo['total_num'],//物品数量
			];
		}
		$post_data['goods'] = json_encode($goods,JSON_UNESCAPED_UNICODE);
		$result =  $this->post($post_data, "/addons/make_speed/core/public/index.php/apis/v2/create_order");
		if($result['error_code'] == 0){
			return $result;
		}
		$this->error = $result['msg'];
		return false;
	}

	/**
     * 取消订单
	*/
	public function cancelOrder($order_no = '')
	{
		$post_data = [
			'token' => $this->_token(),//令牌
			'order_num' => $order_no,//订单号(配送平台)
		];
		$result =  $this->post($post_data, "/addons/make_speed/core/public/index.php/apis/v2/cancel_order");
		if($result['error_code'] == 0){
			return $result;
		}
		$this->error = $result['msg'];
		return false;
	}

    /**
     * 生成token
     */
    private function _token()
	{
		if($token = Cache::get('make_token')){
			return $token;
		}
		$post_data = [
			'token' => $this->config['token'],
			'appid' => $this->config['appid']
		];
		$result =  $this->post($post_data, "/addons/make_speed/core/public/index.php/apis/v2/get_token");
		if(isset($result['token'])){
			// 记录缓存, 70小时，不到3天（token有效期三天）
        	Cache::set('make_token', $result['token'], 3600 * 70);
			return $result['token'];
		}
		return '';
    }

    /**
     * 发送请求,POST
     * @param $url 指定URL完整路径地址
     * @param $data 请求的数据
     */
    private function post($data,$url)
	{
        $url = $this->config['api_url'] . $url;
		// json
        $headers = array(
            'Content-Type: multipart/form-data',
        );
        $curl = curl_init($url);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_TIMEOUT, 3);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        $resp = curl_exec($curl);
        //var_dump( curl_error($curl) );//如果在执行curl的过程中出现异常，可以打开此开关查看异常内容。
        $info = curl_getinfo($curl);
        curl_close($curl);
        if (isset($info['http_code']) && $info['http_code'] == 200) {
            return json_decode($resp, true);
        }
        return false;
    } 
	
}
